import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 路由懒加载
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')

// 用户端路由
const Home = () => import('../views/client/Home.vue')
const RestaurantDetail = () => import('../views/client/RestaurantDetail.vue')
const Order = () => import('../views/client/Order.vue')
const UserCenter = () => import('../views/client/UserCenter.vue')

// 管理端路由
const AdminLayout = () => import('../views/admin/Layout.vue')
const Dashboard = () => import('../views/admin/Dashboard.vue')
const RestaurantManage = () => import('../views/admin/RestaurantManage.vue')
const DishManage = () => import('../views/admin/DishManage.vue')
const OrderManage = () => import('../views/admin/OrderManage.vue')
const UserManage = () => import('../views/admin/UserManage.vue')

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/restaurant/:id',
    name: 'RestaurantDetail',
    component: RestaurantDetail
  },
  {
    path: '/order',
    name: 'Order',
    component: Order,
    meta: { requiresAuth: true }
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: UserCenter,
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        redirect: 'dashboard'
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard
      },
      {
        path: 'restaurant',
        name: 'RestaurantManage',
        component: RestaurantManage
      },
      {
        path: 'dish',
        name: 'DishManage',
        component: DishManage
      },
      {
        path: 'order',
        name: 'OrderManage',
        component: OrderManage
      },
      {
        path: 'user',
        name: 'UserManage',
        component: UserManage
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else if (to.matched.some(record => record.meta.requiresAdmin) && userInfo.role !== 'admin') {
      next({ path: '/home' })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router

